package com.dd.ent.car.common.xrichtext.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.dd.ent.car.MainActivity;
import com.dd.ent.car.R;
import com.dd.ent.car.common.compress.Compressor;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.util.SDCardUtil;
import com.dd.ent.car.common.util.StringUtils;
import com.dd.ent.car.common.xrichtext.EditData;
import com.dd.ent.car.common.xrichtext.RichTextEditor;
import com.dd.ent.car.common.bean.note.Note;
import com.dd.ent.car.common.util.CommonUtil;
import com.dd.ent.car.common.util.DateUtils;
import com.dd.ent.car.common.util.ImageUtils;
import com.dd.ent.car.common.util.ScreenUtils;
import com.dd.ent.car.service.note.NoteService;
import com.duanqu.qupai.utils.FileUtils;
import com.pp.ent.base.concurrent.XLCommand;
import com.pp.ent.base.concurrent.XLThreadPool;
import com.pp.ent.core.manage.UIHandler;
import com.pp.ent.view.annotation.ContentView;
import com.pp.ent.view.annotation.Inject;
import com.pp.ent.view.annotation.OnClick;
import com.pp.ent.view.annotation.ViewInject;

import net.bither.util.NativeUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.iwf.photopicker.PhotoPicker;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 新建笔记
 */
@ContentView(R.layout.activity_new)
public class NewActivity extends com.dd.ent.car.ui.BaseActivity {

    @ViewInject(R.id.et_new_title)
    private EditText et_new_title;

    @ViewInject(R.id.et_new_content)
    private RichTextEditor et_new_content;

    @ViewInject(R.id.titlebar_left)
    private ImageView titlebarLeft;

    @ViewInject(R.id.titlebar_title)
    private TextView titlebarTitle;

    @ViewInject(R.id.titlebar_right_tv1)
    private TextView titlebarRightTv1;

    @ViewInject(R.id.titlebar_right_tv2)
    private TextView titlebarRightTv2;

    @Inject
    private NoteService noteService;
    private Note note;//笔记对象
    private String myTitle;
    private String myContent;
    private String myNoteTime;
    private int flag;//区分是新建笔记还是编辑笔记

    private static final int cutTitleLength = 20;//截取的标题长度

    private ProgressDialog loadingDialog;
    private ProgressDialog insertDialog;
    private int screenWidth;
    private int screenHeight;
    private Subscription subsLoading;
    private Subscription subsInsert;
    public static List<EditData> editDatas;

    public static void startSelf(Context context) {
        startSelf(context, 0, null);
    }

    public static void startSelf(Context context, int flag, Note note) {
        Intent intent = new Intent(context, NewActivity.class);
        intent.putExtra("flag", flag);
        Bundle bundle = new Bundle();
        bundle.putSerializable("note", note);
        intent.putExtra("data", bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();

    }

    private void initData() {
        note = new Note();
        screenWidth = ScreenUtils.getScreenWidth(this);
        screenHeight = ScreenUtils.getScreenHeight(this);

        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);

        loadingDialog = new ProgressDialog(this);
        loadingDialog.setMessage("图片解析中...");
        loadingDialog.setCanceledOnTouchOutside(false);
        Intent intent = getIntent();
        flag = intent.getIntExtra("flag", 0);//0新建，1编辑
        if (flag == 1) {//编辑
            Bundle bundle = intent.getBundleExtra("data");
            note = (Note) bundle.getSerializable("note");
            myTitle = note.getTitle();
            myContent = note.getContent();
            myNoteTime = note.getCreateTime();
            titlebarTitle.setText("编辑笔记");
            et_new_title.setText(note.getTitle());
            et_new_content.post(new Runnable() {
                @Override
                public void run() {
                    //showEditData(note.getContent());
                    et_new_content.clearAllLayout();
                    showDataSync(note.getContent());
                }
            });
        } else {
            titlebarTitle.setText("发帖");
        }
        titlebarRightTv1.setText("预览");
        titlebarRightTv1.setVisibility(View.VISIBLE);
        titlebarRightTv2.setText("图片");
        titlebarRightTv2.setVisibility(View.VISIBLE);
        myNoteTime = DateUtils.date2string(new Date());
    }

    /**
     * 异步方式显示数据
     *
     * @param html
     */
    private void showDataSync(final String html) {
        loadingDialog.show();
        subsLoading = Observable.create(new Observable.OnSubscribe<EditData>() {
            @Override
            public void call(Subscriber<? super EditData> subscriber) {
                showEditData(subscriber, html);
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<EditData>() {

                    @Override
                    public void onCompleted() {
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        e.printStackTrace();
                        showToast("解析错误：图片不存在或已损坏");
                    }

                    @Override
                    public void onNext(EditData editData) {
                        if (editData.imagePath != null) {
                            et_new_content.addImageViewAtIndex(et_new_content.getLastIndex(), editData.imagePath);
                        } else {
                            et_new_content.addEditTextAtIndex(et_new_content.getLastIndex(), editData.inputStr);
                        }
                    }
                });
    }

    /**
     * 显示数据
     */
    protected void showEditData(Subscriber<? super EditData> subscriber, String html) {
        try {
            List<String> textList = StringUtils.cutStringByImgTag(html);
            for (int i = 0; i < textList.size(); i++) {
                String text = textList.get(i);
                EditData editData = new EditData();
                if (text.contains("<img")) {
                    String imagePath = StringUtils.getImgSrc(text);
                    editData.imagePath = imagePath;
                    subscriber.onNext(editData);
                } else {
                    editData.inputStr = text;
                    subscriber.onNext(editData);
                }

            }
            subscriber.onCompleted();
        } catch (Exception e) {
            e.printStackTrace();
            subscriber.onError(e);
        }
    }

    @OnClick({R.id.titlebar_right_tv1, R.id.titlebar_right_tv2, R.id.titlebar_left})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.titlebar_right_tv1:
                jumToPreActivty();
                break;
            case R.id.titlebar_right_tv2:
                callGallery();
                break;
            case R.id.titlebar_left:
                onBackPressed();
                break;
        }
    }

    private void jumToPreActivty() {
        String noteTitle = et_new_title.getText().toString();
        String noteContent = getEditData();
        Log.d("", "noteContent=" + noteContent);
        note.setTitle(noteTitle);
        note.setContent(noteContent);
        note.setCreateTime(DateUtils.date2string(new Date()));
        if (TextUtils.isEmpty(noteTitle)) {
            Toast.makeText(NewActivity.this, "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(noteContent)) {
            Toast.makeText(NewActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        NoteActivity.startSelf(this, NoteActivity.From.PUBLISH, note);
    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     */
    private String getEditData() {
        List<EditData> editList = editDatas = et_new_content.buildEditData();
        StringBuffer content = new StringBuffer();
        for (EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
                Log.d("RichEditor", "commit inputStr=" + itemData.inputStr);
            } else if (itemData.imagePath != null) {
                Log.d("RichEditor", "commit imgePath=" + itemData.imagePath);
                content.append("<img src=\"").append(itemData.imagePath).append("\"/>");
            }
        }
        return content.toString();
    }

    /**
     * 保存数据,=0销毁当前界面，=1不销毁界面，为了防止在后台时保存笔记并销毁，应该只保存笔记
     */
    private void saveNoteData(boolean isBackground) {
        String noteTitle = et_new_title.getText().toString();
        String noteContent = getEditData();
        Log.d("", "noteContent=" + noteContent);
        note.setTitle(noteTitle);
        note.setContent(noteContent);
        note.setCreateTime(DateUtils.date2string(new Date()));
        if (flag == 0) {//新建笔记
            if (noteTitle.length() == 0 && noteContent.length() == 0) {
                return;
            } else {
                noteService.saveNoteDb(note);
            }
        }
    }

    /**
     * 调用图库选择
     */
    private void callGallery() {
        //调用第三方图库选择
        PhotoPicker.builder()
                .setPhotoCount(5)//可选择图片数量
                .setShowCamera(true)//是否显示拍照按钮
                .setShowGif(true)//是否显示动态图
                .setPreviewEnabled(true)//是否可以预览
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 1) {
                    //处理调用系统图库
                } else if (requestCode == PhotoPicker.REQUEST_CODE) {
                    //异步方式插入图片
                    insertImagesSync(data);
                }
            }
        }
    }

    /**
     * 异步方式插入图片
     *
     * @param data
     */
    private void insertImagesSync(final Intent data) {
        insertDialog.show();
        subsInsert = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try {
                    et_new_content.measure(0, 0);
                    int width = ScreenUtils.getScreenWidth(NewActivity.this);
                    int height = ScreenUtils.getScreenHeight(NewActivity.this);
                    ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    //可以同时插入多张图片
                    for (String imagePath : photos) {
//                        File compressedImage = new Compressor(NewActivity.this)
//                                .setMaxWidth(720)
//                                .setMaxHeight(1280)
//                                .setQuality(80)
//                                .setCompressFormat(Bitmap.CompressFormat.JPEG)
//                                .setDestinationDirectoryPath(SDCardUtil.getPictureDir())
//                                .compressToFile(new File(imagePath));

                        File saveFile = new File(SDCardUtil.getPictureDir(), "compress_" + System.currentTimeMillis() + ".jpg");
                        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                        Log.e("===compressImage===", "====开始==压缩==saveFile==" + saveFile.getAbsolutePath());
                        NativeUtil.jniUltimateCompress(bitmap, saveFile.getAbsolutePath());
                        Log.e("===compressImage===", "====完成==压缩==saveFile==" + saveFile.getAbsolutePath());
                        imagePath = saveFile.getAbsolutePath();
                        subscriber.onNext(imagePath);
                    }
                    subscriber.onCompleted();
                } catch (Exception e) {
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        insertDialog.dismiss();
                        et_new_content.addEditTextAtIndex(et_new_content.getLastIndex(), " ");
                        showToast("图片插入成功");
                    }

                    @Override
                    public void onError(Throwable e) {
                        insertDialog.dismiss();
                        showToast("图片插入失败:" + e.getMessage());
                    }

                    @Override
                    public void onNext(String imagePath) {
                        et_new_content.insertImage(imagePath, et_new_content.getMeasuredWidth());
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //如果APP处于后台，或者手机锁屏，则启用密码锁
        if (CommonUtil.isAppOnBackground(getApplicationContext()) ||
                CommonUtil.isLockScreeen(getApplicationContext())) {
            saveNoteData(true);//处于后台时保存数据
        }
    }

    /**
     * 退出处理
     */
    private void dealwithExit() {
        String noteTitle = et_new_title.getText().toString();
        String noteContent = getEditData();
        Log.d("", "noteContent=" + noteContent);
        if (flag == 0) {//新建笔记
            if (noteTitle.length() > 0 || noteContent.length() > 0) {
                saveNoteData(false);
            }
        }
        finish();
    }

    @Override
    public void onBackPressed() {
        dealwithExit();
    }

    @UIHandler(UIConfig.ADD_NOTE_INFO_TO_SERVER_SUCCESS)
    public void addNoteInfoServerSuccessResponse() {
        finish();
    }
}
